/*
 * Downloaded and modified from
 * 
 * http://code.google.com/p/anvm/source/browse/trunk/ANVM_MobileApp/src/anvm/gui/CameraTestActivity.java
 * 
 * No explicit license attached. zbar is licensed under LGPL.
 * 
 * Original header:
 * 
 * Created by lisah0 on 2012-02-24
 * 
 */
package dk.redia.libraryapp;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;

import net.sourceforge.zbar.Config;
import net.sourceforge.zbar.Image;
import net.sourceforge.zbar.ImageScanner;
import net.sourceforge.zbar.Symbol;
import net.sourceforge.zbar.SymbolSet;
import net.sourceforge.zbar.android.CameraTest.CameraPreview;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.hardware.Camera;
import android.hardware.Camera.AutoFocusCallback;
import android.hardware.Camera.PreviewCallback;
import android.hardware.Camera.Size;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;
import android.widget.Toast;
import dk.redia.lib.utils.AppApplication;
import dk.redia.lib.utils.AppConfiguration;
import dk.redia.lib.xmlrpc.XmlRpcClientResultListener;
import dk.redia.lib.xmlrpc.XmlRpcResultDumper;
import dk.redia.lib.xmlrpc.XmlRpcResultUtils;
import dk.redia.libraryapp.model.Externals;
import dk.redia.libraryapp.xmlrpc.library.XmlRpcClient;

public class BarcodeScanActivity extends Activity
{
    protected static final String logTag = "ScannerActivity";
	private Camera mCamera;
    private CameraPreview mPreview;
    private Handler autoFocusHandler;

    ImageScanner scanner;

    private boolean barcodeScanned = false;
    private boolean previewing = true;

    static {
        System.loadLibrary("iconv");
    } 

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.zbar);

        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        autoFocusHandler = new Handler();
        mCamera = getCameraInstance();

        /* Instance barcode scanner */
        scanner = new ImageScanner();
        scanner.setConfig(0, Config.X_DENSITY, 3);
        scanner.setConfig(0, Config.Y_DENSITY, 3);
        
        // Make the close button close the camera activity
        findViewById(R.id.cameraPreviewCancelButton).setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				finish();
			}
		});

        mPreview = new CameraPreview(this, mCamera, previewCb, autoFocusCB);
        FrameLayout preview = (FrameLayout)findViewById(R.id.cameraPreview);
        preview.addView(mPreview);
    }

    public void onPause() {
        super.onPause();
        releaseCamera();
    }

    /** A safe way to get an instance of the Camera object. */
    public static Camera getCameraInstance(){
        Camera c = null;
        try {
            c = Camera.open();
        } catch (Exception e){
        }
        return c;
    }

    private void releaseCamera() {
        if (mCamera != null) {
            previewing = false;
            mCamera.setPreviewCallback(null);
            mCamera.release();
            mCamera = null;
        }
    }

    private Runnable doAutoFocus = new Runnable() {
            public void run() {
                if (previewing)
                    mCamera.autoFocus(autoFocusCB);
            }
        };

    PreviewCallback previewCb = new PreviewCallback() {
            public void onPreviewFrame(byte[] data, Camera camera) {
                Camera.Parameters parameters = camera.getParameters();
                Size size = parameters.getPreviewSize();

                Image barcode = new Image(size.width, size.height, "Y800");
                barcode.setData(data);

                int result = scanner.scanImage(barcode);
                
                if (result != 0) {
                	                	
                	MediaPlayer mp = MediaPlayer.create(BarcodeScanActivity.this, R.raw.scanner_code_scanner_sound);
                	mp.start();
                	mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
						
						@Override
						public void onCompletion(MediaPlayer mp) {
		                	mp.release();
						}
					});
					
                    previewing = false;
                    mCamera.setPreviewCallback(null);
                    mCamera.stopPreview();
                    
                    SymbolSet syms = scanner.getResults();     
                    Log.d(logTag, "Found " + syms.size() + " symbols. Using first");
                    if (syms.size()>0) {
                    	//findViewById(R.id.scannerActivityProgressBar).setVisibility(View.VISIBLE);
                    	//findViewById(R.id.scannerActivityLoadingTextView).setVisibility(View.VISIBLE);
                    	final Symbol sym = syms.iterator().next();
                    	if (sym.getType()==Symbol.QRCODE) {
                    		Log.d(logTag, "Detected QR code");
                    		try { 
                    			new URL(sym.getData()); 
                    		} catch (MalformedURLException e) {
                    			Log.e(logTag, "QR Code does not appear to contain a valid URL");
                    		}
                    		Intent i = new Intent(Intent.ACTION_VIEW);
                    		i.setData(Uri.parse(sym.getData()));
                    		startActivity(i);
                    	} else {
                    		Log.d(logTag, "Scanned tag with type: " + sym.getType());
                    		Log.d(logTag, "Looking up objects for barcode id " + sym.getData());
                    		Intent i = new Intent(BarcodeScanActivity.this, ExternalsListActivity.class);
                    		i.putExtra(ExternalsListActivity.EXTRAS_KEY_EXTERNALS_BARCODE_ID, sym.getData());
                    		startActivity(i);
                    		barcodeScanned = true;
                    	}
                    }
                } else {
                	Log.d(logTag, "There are no symbols?");
                }
            }
        };

    // Mimic continuous auto-focusing
    AutoFocusCallback autoFocusCB = new AutoFocusCallback() {
            public void onAutoFocus(boolean success, Camera camera) {
                autoFocusHandler.postDelayed(doAutoFocus, 1000);
            }
        };
}
